package lion.framework.core.task;

import java.util.Date;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 执行自动任务的类,所有的自动任务是单例的。
 *
 * <pre>
 * time   2013 2013年12月13日 下午3:28:58
 * mail   hl_0074@sina.com
 * </pre>
 *
 * @author lion
 */
public class TaskExecutor implements Runnable {

	private Log log = LogFactory.getLog(TaskExecutor.class);

	private LinkedBlockingQueue<ISchedule> scheduleQueue;

	public TaskExecutor(LinkedBlockingQueue<ISchedule> scheduleQueue) {

		this.scheduleQueue = scheduleQueue;
	}

	@Override
	public void run() {

		ISchedule schedule;
		try {
			schedule = scheduleQueue.take();

		} catch (InterruptedException e1) {
			return;
		}
		if (schedule == null) { return; }

		schedule.setStatus(TaskStatus.RUNNING);
		schedule.setLastRunTime(new Date());
		try {
			schedule.getTask().run(schedule.getArgs());
		} catch (Throwable e) {
			log.error("", e);
			schedule.setError(e);
		} finally {
			schedule.setStatus(TaskStatus.WAITING);
			schedule.setExecutedTimes(schedule.getExecutedTimes() + 1);
			schedule.sync();
		}
	}
}
